import { Toast } from "antd-mobile";
import axios from "axios";
import type { AxiosInstance, AxiosHeaders } from "axios";

export const createRequestInstance = (baseURL: string): AxiosInstance => {
  const httpInstance: AxiosInstance = axios.create({
    baseURL,
    timeout: 60000,
  });

  httpInstance.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem("token");
      if (token) {
        if (!config.headers) {
          config.headers = {} as AxiosHeaders;
        }
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  httpInstance.interceptors.response.use(
    (response) => {
      const resT = response.data;
      if (resT.code && resT.code != 200) {
        Toast.show({
          icon: "fail",
          content: resT.msg,
        });
      }
      return response;
    },
    (error) => {
      const response = error.response;
      if (response?.status == 401) {
        Toast.show({
          icon: "fail",
          content: "登陆过期了，请重新登陆",
        });
        localStorage.clear();
        window.location.replace("/login");
        return false;
      } else {
        const resT = response?.data;
        const msg = resT?.msg || "请求失败";
        Toast.show({
          icon: "fail",
          content: msg,
        });
      }
      // return Promise.reject(error);
      return response;
    }
  );
  return httpInstance;
};

// const baseUrl = import.meta.env.VITE_API_URL;
const baseURL = process.env.UMI_APP_BASE_URL || "";
const apiRequest = createRequestInstance(baseURL);

export interface RequestResponse<T> {
  code: number;
  data: T;
  message: string;
}

const request = {
  async get<T>(url: string, params?: any): Promise<RequestResponse<T>> {
    const response = await apiRequest.get(url, { params });
    return response.data;
  },
  async post<T>(
    url: string,
    params?: any,
    data?: any
  ): Promise<RequestResponse<T>> {
    const response = await apiRequest.post(url, params, data);
    return response.data;
  },
};

export default request;
